package org.devocean.groupbuying.utils;

public class Utils {

	public static Pagination paginate(Integer index, Integer total,
			Integer showed) {
		Integer next = index + 1;
		Integer prev = index - 1;

		if (total < showed) {
			showed = total;
		}

		int min = index - (showed / 2);

		if (min <= 0) {
			min = 1;
		}

		int max = index + (showed / 2);

		if (max < showed) {
			max = showed;
		}

		if (max > total) {
			max = total;
		}

		if (max - min < showed) {
			min = max - showed + 1;
		}

		if (next > total) {
			next = total;
		}
		if (prev <= 0) {
			prev = 1;
		}

		Pagination p = new Pagination();
		p.setFirst("1");
		p.setPrevious(prev.toString());
		for (Integer i = min; i <= max; i++) {
			p.getPages().add(i.toString());
		}
		p.setNext(next.toString());
		p.setLast(total.toString());

		return p;
	}

}
